/*
 * Copyright (C) 2015 tyrantgit
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.technology.lovedemo.like;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.example.technology.lovedemo.BasEvaluator;
import com.example.technology.lovedemo.R;

import java.util.Random;


/**
 * 飘心动画界面布局类
 * 通过动画控制每个心形界面的显示
 * TCPathAnimator 控制显示路径
 * TCHeartView 单个心形界面
 */
public class TCHeartLayout extends RelativeLayout {

    private TCAbstractPathAnimator mAnimator;
    AnimatorSet animatorSet = new AnimatorSet();
    private int defStyleAttr = 0;

    private int textHight;
    private int dHeight;
    private int dWidth;
    private int initX;
    private int pointx;
    float[] num = {-30, -20, 0, 20, 30};//随机心形图片角度
    private int mWidth;
    private int mHeight;
    private Handler mHandler;
    public TCHeartLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mHandler = new Handler(Looper.getMainLooper());
        findViewById(context);
        initHeartDrawable();
        init(attrs, defStyleAttr);
    }

    private void findViewById(Context context) {
        LayoutInflater.from(context).inflate(R.layout.layout_periscope, this);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.live_ic_like);
        dHeight = bitmap.getWidth();
        dWidth = bitmap.getHeight();
        textHight = sp2px(getContext(), 20) + dHeight / 2;

        pointx = dWidth;//随机上浮方向的x坐标

        bitmap.recycle();
    }

    private static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }


    private void init(AttributeSet attrs, int defStyleAttr) {
        final TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.HeartLayout, defStyleAttr, 0);

        //todo:获取确切值
        initX = 30;
        if (pointx <= initX && pointx >= 0) {
            pointx -= 10;
        } else if (pointx >= -initX && pointx <= 0) {
            pointx += 10;
        } else pointx = initX;


        mAnimator = new TCPathAnimator(
                TCAbstractPathAnimator.Config.fromTypeArray(a, initX, textHight, pointx, dWidth, dHeight));
        a.recycle();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mWidth = (int) (event.getRawX() - (event.getRawX()-event.getX()));
        mHeight = (int) (event.getRawY() - (event.getRawY()-event.getY()));
        Log.d("tgw", "onTouchEvent: mWidth:"+mWidth+"--mHeight:"+mHeight+"--event.getX():"+event.getX()+"--event.getY():"+event.getY()+"--event.getRawX():"+event.getRawX()+"--event.getY():"+event.getY());

        return super.onTouchEvent(event);

    }

    private  AnimatorSet getAnimatorSet(TCHeartView iv) {

        // 1.alpha动画,没啥效果被 贝塞尔的差值动画替代了
        ObjectAnimator alpha = ObjectAnimator.ofFloat(iv, "alpha", 1.5f, 0.5f);

        // 2.缩放动画
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(iv, "scaleX",0.2f, 1f, 1.2f, 1.8f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(iv, "scaleY", 0.2f, 1f, 1.2f, 1.8f);

        //3.随机角度
        ObjectAnimator rotation =rotation(iv, 0, 0, num[new Random().nextInt(4)]);
        // 动画集合
        AnimatorSet set = new AnimatorSet();
        set.playTogether(alpha, scaleX, scaleY,rotation);
        set.setInterpolator(new DecelerateInterpolator());
        set.setDuration(4000);

        // 贝塞尔曲线动画
        ValueAnimator bzier = getBzierAnimator(iv);

        AnimatorSet set2 = new AnimatorSet();
        set2.playTogether(set, bzier);
        set2.setTarget(iv);
        return set2;
    }

    public  ObjectAnimator rotation(View view, long time, long delayTime, float... values) {
        ObjectAnimator rotation = ObjectAnimator.ofFloat(view, "rotation", values);
        rotation.setDuration(time);
        rotation.setStartDelay(delayTime);
        rotation.setInterpolator(new TimeInterpolator() {
            @Override
            public float getInterpolation(float input) {
                return input;
            }
        });
        return rotation;
    }
    /**
     * 贝塞尔动画
     */
    private  ValueAnimator getBzierAnimator(final TCHeartView iv) {
        // TODO Auto-generated method stub
        PointF[] PointFs = getPointFs(iv); // 4个点的坐标
        for (int i=0;i<PointFs.length;i++){
            Log.d("tgw4个点的坐标", "onTouchEvent: mWidth:"+PointFs[i].x+"--mHeight:"+PointFs[i].y);
        }
        BasEvaluator evaluator = new BasEvaluator(PointFs[1], PointFs[2]);
        ValueAnimator valueAnim = ValueAnimator.ofObject(evaluator, PointFs[0], PointFs[3]);
        valueAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // TODO Auto-generated method stub
                PointF p = (PointF) animation.getAnimatedValue();
                iv.setX(p.x);
                iv.setY(p.y);
                iv.setAlpha(1 - animation.getAnimatedFraction()); // 透明度

            }
        });
        valueAnim.setTarget(iv);
//        AccelerateDecelerateInterpolator	@android:anim/accelerate_decelerate_interpolator	其变化开始和结束速率较慢，中间加速
//        AccelerateInterpolator	@android:anim/accelerate_interpolator	其变化开始速率较慢，后面加速
//        DecelerateInterpolator	@android:anim/decelerate_interpolator	其变化开始速率较快，后面减速
//        LinearInterpolator	@android:anim/linear_interpolator	其变化速率恒定
        Interpolator interpolator = new DecelerateInterpolator();
        valueAnim.setDuration(4000);
        valueAnim.setInterpolator(interpolator);
//        valueAnim.setInterpolator(interpolators[new Random().nextInt(4)]);
        return valueAnim;
    }

    private  PointF[] getPointFs(TCHeartView iv) {
        // TODO Auto-generated method stub
        PointF[] PointFs = new PointF[4];
        PointFs[0] = new PointF(); // p0
        PointFs[0].x = ((int) mWidth);
        PointFs[0].y = mHeight;

        PointFs[1] = new PointF(); // p1
        PointFs[1].x = new Random().nextInt(mWidth);
        PointFs[1].y = new Random().nextInt(mHeight / 2) + mHeight / 2;

        PointFs[2] = new PointF(); // p2
        PointFs[2].x = new Random().nextInt(mWidth);
        PointFs[2].y = new Random().nextInt(mHeight / 2);

        PointFs[3] = new PointF(); // p3
        PointFs[3].x = new Random().nextInt(mWidth);
//        PointFs[3].x = new Random().nextInt(mWidth);   PointFs[3].设置0永远左上角
        PointFs[3].y = 0;
        return PointFs;
    }


    public void clearAnimation() {
        for (int i = 0; i < getChildCount(); i++) {
            getChildAt(i).clearAnimation();
        }
        removeAllViews();
    }
    public void resourceLoad(){
        mHearts = new Bitmap[drawableIds.length];
        mHeartsDrawable = new BitmapDrawable[drawableIds.length];
        for (int i =0;i < drawableIds.length;i++){
            mHearts[i] = BitmapFactory.decodeResource(getResources(), drawableIds[i]);
            mHeartsDrawable[i] = new BitmapDrawable(getResources(), mHearts[i]);
        }
    }
    private static int[] drawableIds = new int[]{R.mipmap.zan1, R.mipmap.zan2, R.mipmap.zan3, R.drawable.heart_red};
//    private static int[] drawableIds = new int[]{R.mipmap.zan1, R.mipmap.zan1, R.mipmap.zan1, R.drawable.heart_red, R.drawable.heart4, R.drawable.heart5, R.drawable.heart6, R.drawable.heart7, R.drawable.heart8,};
    private Random mRandom = new Random();
    private static Drawable[] sDrawables;
    private Bitmap[] mHearts;
    private BitmapDrawable[] mHeartsDrawable;
    private void initHeartDrawable() {
        int size = drawableIds.length;
        sDrawables = new Drawable[size];
        for (int i = 0 ; i < size; i++) {
            sDrawables[i] = getResources().getDrawable(drawableIds[i]);
        }
        resourceLoad();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        mWidth = widthMeasureSpec;
        mHeight = heightMeasureSpec;
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
    public static int[] measureView(final View view) {
        ViewGroup.LayoutParams lp = view.getLayoutParams();
        if (lp == null) {
            lp = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );
        }
        int widthSpec = ViewGroup.getChildMeasureSpec(0, 0, lp.width);
        int lpHeight = lp.height;
        int heightSpec;
        if (lpHeight > 0) {
            heightSpec = View.MeasureSpec.makeMeasureSpec(lpHeight, View.MeasureSpec.EXACTLY);
        } else {
            heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        }
        view.measure(widthSpec, heightSpec);
        return new int[]{view.getMeasuredWidth(), view.getMeasuredHeight()};
    }

    public void addFavor() {
        final TCHeartView heartView = new TCHeartView(getContext());
        heartView.setDrawable(mHeartsDrawable[mRandom.nextInt(4)]);
        mWidth= measureView(heartView)[0];
        mHeight= measureView(heartView)[1];
//        heartView.setImageResource(mRandom.nextInt(4));

//        mWidth = heartView.getWidth();
//        mHeight = heartView.getHeight();

        Log.d("tgw1", "addFavor: "+mWidth+"--mHeight"+mHeight);
        //自己加的
        if (mHeight >1 && mWidth >1) {
            addView(heartView, new ViewGroup.LayoutParams(100, 100));
            animatorSet = getAnimatorSet(heartView);
            animatorSet.start();
            animatorSet.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            removeView(heartView);
                        }
                    });

//                    removeViewInLayout(heartView);
                }
            });
        }


//        heartView.setDrawable(mHeartsDrawable[mRandom.nextInt(8)]);
//        heartView.setImageDrawable(sDrawables[random.nextInt(8)]);
//        init(attrs, defStyleAttr);
        //注意如果放出这里则  上面注释为 ---  //自己加的 应该被注释
//        mAnimator.start(heartView, this);

    }

    public void addFavor(int w,int h) {
        final TCHeartView heartView = new TCHeartView(getContext());
        heartView.setDrawable(mHeartsDrawable[mRandom.nextInt(4)]);
        mWidth= measureView(heartView)[0];
        mHeight= measureView(heartView)[1];
//        heartView.setImageResource(mRandom.nextInt(4));

//        mWidth = heartView.getWidth();
//        mHeight = heartView.getHeight();
        mWidth= w/2;
        mHeight= h;
        Log.d("tgw1", "addFavor: "+mWidth+"--mHeight"+mHeight);
        //自己加的
        if (mHeight >1 && mWidth >1) {
            addView(heartView, new ViewGroup.LayoutParams(100, 100));
            animatorSet = getAnimatorSet(heartView);
            animatorSet.start();
            animatorSet.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            removeView(heartView);
                        }
                    });

//                    removeViewInLayout(heartView);
                }
            });
        }


//        heartView.setDrawable(mHeartsDrawable[mRandom.nextInt(8)]);
//        heartView.setImageDrawable(sDrawables[random.nextInt(8)]);
//        init(attrs, defStyleAttr);
        //注意如果放出这里则  上面注释为 ---  //自己加的 应该被注释
//        mAnimator.start(heartView, this);

    }

    public void addFavor(int w,int h,int num) {
        mWidth = w/2;
        mHeight = h;
        num =mRandom.nextInt(4);
        //自己加的
        if (mHeight >1 && mWidth >1) {  //防止宽高为0时 贝塞尔的取值数组越界
            for (int i = 0;i<=num;i++){
                final TCHeartView heartView = new TCHeartView(getContext());
                heartView.setDrawable(mHeartsDrawable[mRandom.nextInt(4)]);
                addView(heartView, new ViewGroup.LayoutParams(100, 100));
                animatorSet = getAnimatorSet(heartView);
                animatorSet.start();
                animatorSet.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        removeView(heartView);
//                    removeViewInLayout(heartView);
                    }
                });
            }

        }

    }
    public void addFavor(int view) {
        TCHeartView heartView = new TCHeartView(getContext());
        heartView.setDrawable(mHeartsDrawable[mRandom.nextInt(4)]);
        mAnimator.start(heartView, this);
    }

}
